import 'package:flutter/material.dart';
import '../services/course_import_service.dart';
import '../app_data_manager.dart';
import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart' as path;
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter/foundation.dart';
import 'package:share_plus/share_plus.dart';

class ProfilePage extends StatelessWidget {
  const ProfilePage({super.key});

  Future<String?> _getSavePath(BuildContext context) async {
    try {
      debugPrint('开始请求存储权限...');
      
      // 检查 Android 版本
      if (Platform.isAndroid) {
        // 请求存储权限
        Map<Permission, PermissionStatus> statuses = await [
          Permission.storage,
          Permission.manageExternalStorage,
          Permission.photos,
          Permission.videos,
          Permission.mediaLibrary,
        ].request();

        // 详细检查每个权限的状态
        statuses.forEach((permission, status) {
          debugPrint('权限 $permission 状态: $status');
        });

        // 检查是否所有权限都已授予
        bool allGranted = statuses.values.every((status) => status.isGranted);
        debugPrint('所有权限是否已授予: $allGranted');

        if (!allGranted) {
          debugPrint('权限未全部授予，尝试请求管理外部存储权限');
          // 特别检查管理外部存储权限
          final manageStatus = await Permission.manageExternalStorage.status;
          debugPrint('管理外部存储权限状态: $manageStatus');

          if (!manageStatus.isGranted) {
            if (context.mounted) {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('需要存储权限才能保存文件，请在设置中授予权限'),
                  backgroundColor: Colors.red,
                  duration: Duration(seconds: 3),
                  action: SnackBarAction(
                    label: '去设置',
                    onPressed: openAppSettings,
                    textColor: Colors.white,
                  ),
                ),
              );
            }
            return null;
          }
        }
      }

      // 获取外部存储目录
      final externalDir = await getExternalStorageDirectory();
      if (externalDir == null) {
        debugPrint('无法获取外部存储目录');
        if (context.mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('无法访问外部存储'),
              backgroundColor: Colors.red,
            ),
          );
        }
        return null;
      }

      debugPrint('外部存储目录: ${externalDir.path}');

      // 获取外部存储的根目录
      final rootDir = externalDir.parent.parent.parent;
      final downloadDir = Directory('${rootDir.path}/Download');
      if (!await downloadDir.exists()) {
        debugPrint('创建下载目录');
        await downloadDir.create(recursive: true);
      }

      // 创建备份文件夹
      final backupDir = Directory('${downloadDir.path}/AppBackup');
      if (!await backupDir.exists()) {
        debugPrint('创建备份文件夹: ${backupDir.path}');
        await backupDir.create(recursive: true);
      }

      // 生成默认文件名
      final timestamp = DateTime.now().millisecondsSinceEpoch;
      final defaultFileName = 'app_data_$timestamp.json';
      final defaultPath = '${backupDir.path}/$defaultFileName';
      debugPrint('默认保存路径: $defaultPath');

      // 显示保存对话框
      if (context.mounted) { 
        final result = await showDialog<String>(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('选择保存位置'),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text('默认保存位置：'),
                Text(
                  defaultPath,
                  style: const TextStyle(
                    fontSize: 12,
                    color: Colors.grey,
                  ),
                ),
                const SizedBox(height: 16),
                const Text('是否使用默认位置？'),
              ],
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(defaultPath),
                child: const Text('使用默认位置'),
              ),
              TextButton(
                onPressed: () async {
                  Navigator.of(context).pop(null);
                  debugPrint('用户选择自定义位置');
                  // 使用 image_picker 选择文件
                  final ImagePicker picker = ImagePicker();
                  final XFile? file = await picker.pickImage(
                    source: ImageSource.gallery,
                    requestFullMetadata: true,
                  );
                  if (file != null) {
                    debugPrint('用户选择的文件: ${file.path}');
                    // 获取所选文件的目录
                    final selectedDir = path.dirname(file.path);
                    // 创建备份文件夹
                    final backupDir = Directory('$selectedDir/AppBackup');
                    if (!await backupDir.exists()) {
                      debugPrint('创建自定义备份文件夹: ${backupDir.path}');
                      await backupDir.create(recursive: true);
                    }
                    final newPath = '${backupDir.path}/$defaultFileName';
                    debugPrint('最终保存路径: $newPath');
                    if (context.mounted) {
                      Navigator.of(context).pop(newPath);
                    }
                  } else {
                    debugPrint('用户取消了文件选择');
                  }
                },
                child: const Text('选择其他位置'),
              ),
            ],
          ),
        );

        debugPrint('对话框结果: $result');
        return result;
      }
      return null;
    } catch (e, stackTrace) {
      debugPrint('获取保存路径时发生错误: $e');
      debugPrint('错误堆栈: $stackTrace');
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('获取保存路径失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
      return null;
    }
  }

  Future<void> _exportAndShare(BuildContext context) async {
    try {
      debugPrint('开始导出数据...');
      
      // 显示加载对话框
      if (context.mounted) {
        showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) => const Center(
            child: CircularProgressIndicator(),
          ),
        );
      }

      // 获取导出数据
      debugPrint('获取导出数据...');
      final exportData = await AppDataManager().exportAllData();
      final jsonStr = json.encode(exportData);
      debugPrint('数据编码完成，大小: ${jsonStr.length} 字节');

      // 获取临时目录
      final tempDir = await getTemporaryDirectory();
      final timestamp = DateTime.now().millisecondsSinceEpoch;
      final fileName = 'app_data_$timestamp.json';
      final filePath = '${tempDir.path}/$fileName';

      // 保存文件
      debugPrint('保存文件到临时目录: $filePath');
      final file = File(filePath);
      await file.writeAsString(jsonStr);

      // 验证文件
      if (!await file.exists()) {
        throw Exception('文件保存失败：文件不存在');
      }

      final fileSize = await file.length();
      if (fileSize == 0) {
        throw Exception('文件保存失败：文件大小为0');
      }

      // 关闭加载对话框
      if (context.mounted) {
        Navigator.of(context).pop();
      }

      // 分享文件
      debugPrint('开始分享文件...');
      await Share.shareXFiles(
        [XFile(filePath)],
        text: '应用数据备份',
        subject: '应用数据备份文件',
      );

    } catch (e, stackTrace) {
      debugPrint('导出数据失败: $e');
      debugPrint('错误堆栈: $stackTrace');
      if (context.mounted) {
        Navigator.of(context).pop(); // 关闭加载对话框
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: const Row(
              children: [
                Icon(Icons.error, color: Colors.red),
                SizedBox(width: 8),
                Text('导出失败'),
              ],
            ),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text('导出过程中发生错误：'),
                const SizedBox(height: 8),
                Text(
                  e.toString(),
                  style: const TextStyle(
                    fontSize: 12,
                    color: Colors.red,
                  ),
                ),
              ],
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: const Text('确定'),
              ),
            ],
          ),
        );
      }
    }
  }

  Future<void> _importCourses(BuildContext context) async {
    try {
      debugPrint('开始导入课表...');
      
      // 显示加载对话框
      if (context.mounted) {
        showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) => const Center(
            child: CircularProgressIndicator(),
          ),
        );
      }

      // 导入课表
      final success = await CourseImportService.importCourses();

      // 关闭加载对话框
      if (context.mounted) {
        Navigator.of(context).pop();
      }

      if (success) {
        if (context.mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('课表导入成功'),
              backgroundColor: Colors.green,
            ),
          );
        }
      } else {
        if (context.mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('课表导入失败，请确保选择了正确的ICS文件'),
              backgroundColor: Colors.red,
            ),
          );
        }
      }
    } catch (e, stackTrace) {
      debugPrint('导入课表失败: $e');
      debugPrint('错误堆栈: $stackTrace');
      if (context.mounted) {
        Navigator.of(context).pop(); // 关闭加载对话框
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('导入课表失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('个人中心'),
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 0,
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            // 顶部个人信息卡片
            Container(
              width: double.infinity,
              padding: const EdgeInsets.symmetric(vertical: 30, horizontal: 20),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [
                    Colors.blue[400]!,
                    Colors.blue[600]!,
                  ],
                ),
                borderRadius: const BorderRadius.only(
                  bottomLeft: Radius.circular(30),
                  bottomRight: Radius.circular(30),
                ),
              ),
              child: Column(
                children: [
                  // 头像
                  Container(
                    width: 100,
                    height: 100,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: Colors.white,
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.1),
                          blurRadius: 10,
                          offset: const Offset(0, 5),
                        ),
                      ],
                    ),
                    child: const Icon(
                      Icons.person,
                      size: 50,
                      color: Colors.blue,
                    ),
                  ),
                  const SizedBox(height: 20),
                  // 用户名
                  const Text(
                    '用户名',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 5),
                  // 个性签名
                  const Text(
                    '自律成就更好的自己',
                    style: TextStyle(
                      color: Colors.white70,
                      fontSize: 14,
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 20),
            // 菜单列表
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: Column(
                children: [
                  _buildMenuItem(
                    icon: Icons.star,
                    title: '成就',
                    subtitle: '查看你的自律成就',
                    onTap: () {},
                  ),
                  _buildMenuItem(
                    icon: Icons.history,
                    title: '历史记录',
                    subtitle: '查看历史自律数据',
                    onTap: () {},
                  ),
                  _buildMenuItem(
                    icon: Icons.analytics,
                    title: '数据分析',
                    subtitle: '查看详细的数据分析',
                    onTap: () {},
                  ),
                  _buildMenuItem(
                    icon: Icons.settings,
                    title: '设置',
                    subtitle: '个性化你的体验',
                    onTap: () {},
                  ),
                  _buildMenuItem(
                    icon: Icons.help,
                    title: '帮助与反馈',
                    subtitle: '获取帮助或提交反馈',
                    onTap: () {},
                  ),
                  _buildMenuItem(
                    icon: Icons.file_download,
                    title: '导出数据',
                    subtitle: '导出所有应用数据',
                    onTap: () => _exportAndShare(context),
                  ),
                  _buildMenuItem(
                    icon: Icons.file_upload,
                    title: '导入数据',
                    subtitle: '导入应用数据备份',
                    onTap: () async {
                      try {
                        // 选择文件
                        final ImagePicker picker = ImagePicker();
                        final XFile? file = await picker.pickMedia();
                        
                        if (file == null) return;
                        
                        // 读取文件内容
                        final jsonStr = await file.readAsString();
                        final importData = json.decode(jsonStr) as Map<String, dynamic>;
                        
                        // 显示确认对话框
                        if (context.mounted) {
                          final confirmed = await showDialog<bool>(
                            context: context,
                            builder: (context) => AlertDialog(
                              title: const Text('确认导入'),
                              content: const Text('导入数据将覆盖当前所有数据，是否继续？'),
                              actions: [
                                TextButton(
                                  onPressed: () => Navigator.of(context).pop(false),
                                  child: const Text('取消'),
                                ),
                                TextButton(
                                  onPressed: () => Navigator.of(context).pop(true),
                                  child: const Text('确认'),
                                ),
                              ],
                            ),
                          );
                          
                          if (confirmed != true) return;
                        }
                        
                        // 显示加载对话框
                        if (context.mounted) {
                          showDialog(
                            context: context,
                            barrierDismissible: false,
                            builder: (context) => const Center(
                              child: CircularProgressIndicator(),
                            ),
                          );
                        }
                        
                        // 导入数据
                        await AppDataManager().importAllData(importData);
                        
                        // 关闭加载对话框
                        if (context.mounted) {
                          Navigator.of(context).pop();
                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(
                              content: Text('数据导入成功'),
                              backgroundColor: Colors.green,
                            ),
                          );
                        }
                      } catch (e) {
                        print('导入数据失败: $e');
                        if (context.mounted) {
                          Navigator.of(context).pop(); // 关闭加载对话框
                          ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(
                              content: Text('导入数据失败: $e'),
                              backgroundColor: Colors.red,
                            ),
                          );
                        }
                      }
                    },
                  ),
                  _buildMenuItem(
                    icon: Icons.import_export,
                    title: '导入课表',
                    subtitle: '从ICS文件导入课表数据',
                    onTap: () => _importCourses(context),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildMenuItem({
    required IconData icon,
    required String title,
    required String subtitle,
    required VoidCallback onTap,
  }) {
    return Card(
      margin: const EdgeInsets.only(bottom: 15),
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(15),
      ),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(15),
        child: Padding(
          padding: const EdgeInsets.all(15),
          child: Row(
            children: [
              // 图标
              Container(
                width: 50,
                height: 50,
                decoration: BoxDecoration(
                  color: Colors.blue.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Icon(
                  icon,
                  color: Colors.blue,
                  size: 24,
                ),
              ),
              const SizedBox(width: 15),
              // 文字信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      title,
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      subtitle,
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey[600],
                      ),
                    ),
                  ],
                ),
              ),
              // 箭头图标
              Icon(
                Icons.chevron_right,
                color: Colors.grey[400],
              ),
            ],
          ),
        ),
      ),
    );
  }
} 